#!/usr/bin/env node

import { execSync } from 'child_process'
import { existsSync, mkdirSync, writeFileSync, readFileSync } from 'fs'
import { join } from 'path'
import { platform, arch } from 'os'

const BUILD_DIR = 'dist-electron'
const LOG_FILE = join(BUILD_DIR, 'build.log')
const PACKAGE_JSON = 'package.json'

// 确保构建目录存在
if (!existsSync(BUILD_DIR)) {
  mkdirSync(BUILD_DIR, { recursive: true })
}

// 读取package.json获取版本信息
const packageInfo = JSON.parse(readFileSync(PACKAGE_JSON, 'utf-8'))

console.log('🚀 Starting Electron build process...')
console.log(`📦 Building ${packageInfo.name} v${packageInfo.version}`)
console.log(`🖥️  Current platform: ${platform()}-${arch()}\n`)

const startTime = Date.now()
let buildLog = `Build started at: ${new Date().toISOString()}\n`
buildLog += `Package: ${packageInfo.name} v${packageInfo.version}\n`
buildLog += `Platform: ${platform()}-${arch()}\n\n`

// 构建配置
const BUILD_CONFIGS = {
  win: {
    command: '--win',
    description: 'Windows (x64, ia32)',
    platforms: ['win32']
  },
  mac: {
    command: '--mac',
    description: 'macOS (x64, arm64)',
    platforms: ['darwin']
  },
  linux: {
    command: '--linux',
    description: 'Linux (x64)',
    platforms: ['linux']
  },
  all: {
    command: '--win --mac --linux',
    description: 'All platforms',
    platforms: ['win32', 'darwin', 'linux']
  }
}

function validatePlatform(targetPlatform, currentPlatform) {
  const config = BUILD_CONFIGS[targetPlatform]
  if (!config) return true
  
  // 检查是否可以在当前平台构建目标平台
  if (targetPlatform === 'mac' && currentPlatform !== 'darwin') {
    console.log('⚠️  Warning: Building for macOS on non-macOS platform may require additional setup')
  }
  
  return true
}

function getEnvironmentInfo() {
  const info = {
    node: process.version,
    platform: platform(),
    arch: arch(),
    electron: packageInfo.devDependencies?.electron || 'unknown',
    electronBuilder: packageInfo.devDependencies?.['electron-builder'] || 'unknown'
  }
  
  console.log('🔧 Environment Info:')
  console.log(`   Node.js: ${info.node}`)
  console.log(`   Electron: ${info.electron}`)
  console.log(`   Electron Builder: ${info.electronBuilder}`)
  console.log('')
  
  return info
}

try {
  const envInfo = getEnvironmentInfo()
  buildLog += `Environment: Node.js ${envInfo.node}, Electron ${envInfo.electron}\n\n`
  
  // 1. 清理之前的构建
  console.log('🧹 Cleaning previous build...')
  execSync('pnpm run build', { stdio: 'inherit' })
  buildLog += 'Web build completed successfully\n'
  
  // 2. 检查平台参数
  const targetPlatform = process.argv[2]?.toLowerCase()
  let buildCommand = 'electron-builder'
  let buildDescription = 'current platform'
  
  if (targetPlatform && BUILD_CONFIGS[targetPlatform]) {
    const config = BUILD_CONFIGS[targetPlatform]
    buildCommand += ` ${config.command}`
    buildDescription = config.description
    
    validatePlatform(targetPlatform, platform())
  } else if (targetPlatform) {
    console.log(`⚠️  Unknown platform: ${targetPlatform}`)
    console.log('Available platforms: win, mac, linux, all')
    console.log('Building for current platform...\n')
  }
  
  // 3. 显示构建信息
  console.log(`📦 Building for: ${buildDescription}`)
  console.log(`🔨 Command: ${buildCommand}`)
  console.log('')
  
  // 4. 构建 Electron 应用
  console.log('⚡ Starting Electron build...')
  const buildStartTime = Date.now()
  
  execSync(buildCommand, { 
    stdio: 'inherit',
    env: {
      ...process.env,
      // 设置构建环境变量
      NODE_ENV: 'production',
      ELECTRON_BUILDER_CACHE: join(process.cwd(), 'node_modules/.cache/electron-builder')
    }
  })
  
  const buildEndTime = Date.now()
  const buildDuration = (buildEndTime - buildStartTime) / 1000
  
  buildLog += `Electron build completed successfully\n`
  buildLog += `Command: ${buildCommand}\n`
  buildLog += `Build duration: ${buildDuration.toFixed(2)}s\n`
  
  // 5. 显示构建结果
  const totalDuration = (Date.now() - startTime) / 1000
  
  console.log('\n✅ Build completed successfully!')
  console.log(`⏱️  Total time: ${totalDuration.toFixed(2)}s`)
  console.log(`📁 Output directory: ${BUILD_DIR}`)
  
  // 显示生成的文件
  if (existsSync(BUILD_DIR)) {
    console.log('\n📦 Generated files:')
    try {
      const files = execSync(`ls -la "${BUILD_DIR}"`, { encoding: 'utf-8' })
      console.log(files)
    } catch (e) {
      // Windows fallback
      try {
        const files = execSync(`dir "${BUILD_DIR}"`, { encoding: 'utf-8' })
        console.log(files)
      } catch (e2) {
        console.log('   (Unable to list files)')
      }
    }
  }
  
  buildLog += `Total duration: ${totalDuration.toFixed(2)}s\n`
  buildLog += `Build finished at: ${new Date().toISOString()}\n`
  
  // 写入构建日志
  writeFileSync(LOG_FILE, buildLog)
  console.log(`\n📝 Build log saved to: ${LOG_FILE}`)
  
} catch (error) {
  console.error('\n❌ Build failed!')
  console.error(`Error: ${error.message}`)
  
  if (error.stdout) {
    console.error('stdout:', error.stdout.toString())
  }
  if (error.stderr) {
    console.error('stderr:', error.stderr.toString())
  }
  
  buildLog += `Build failed: ${error.message}\n`
  if (error.stdout) buildLog += `stdout: ${error.stdout.toString()}\n`
  if (error.stderr) buildLog += `stderr: ${error.stderr.toString()}\n`
  buildLog += `Build failed at: ${new Date().toISOString()}\n`
  
  writeFileSync(LOG_FILE, buildLog)
  console.log(`\n📝 Error log saved to: ${LOG_FILE}`)
  
  process.exit(1)
}